import pymysql
import traceback

class DB:
    def __init__(self,host,user,password,database):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
    def connect(self):
        # 实例化db对象
        self.db = pymysql.connect(user=self.user,password=self.password,host=self.host,database=self.database,cursorclass =
        pymysql.cursors.DictCursor)
        # 创建游标
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()

    def searchOne(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            return result
        except:
            traceback.print_exc()
            self.db.rollback()
            return result
        finally:
            self.close()

    def searchAll(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            return result
        except:
            traceback.print_exc()
            self.db.rollback()
            return result
        finally:
            self.close()

    def __edit(self,sql):
        self.connect()
        result = 0
        try:
            self.cursor.execute(sql)
            self.db.commit()
            result = 1
            return result
        except:
            self.db.rollback()
            traceback.print_exc()
            return result
        finally:
            self.close()

    def insert(self,sql):
        return self.__edit(sql)

    def update(self,sql):
        return self.__edit(sql)

    def delete(self,sql):
        return self.__edit(sql)


d1 = DB("120.55.103.65","root","1965331442Xby@","crmeb")
#result = d1.searchOne("select * from eb_user_group where group_name='张三1'")






